package com.car.rental.user.config;

import com.car.rental.user.entity.User;
import com.car.rental.user.entity.UserRole;
import com.car.rental.user.mapper.UserMapper;
import com.car.rental.user.mapper.UserRoleMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@Component
@RequiredArgsConstructor
public class AdminInitializer implements CommandLineRunner {

    private final UserMapper userMapper;
    private final UserRoleMapper userRoleMapper;
    private final PasswordEncoder passwordEncoder;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void run(String... args) {
        // 检查超级管理员是否已存在
        User admin = userMapper.selectByUsername("superadmin");
        if (admin == null) {
            log.info("开始初始化超级管理员账号...");

            // 创建超级管理员用户
            admin = new User();
            admin.setUsername("superadmin");
            admin.setPassword(passwordEncoder.encode("admin123")); // 使用相同的密码加密方式
            admin.setNickname("超级管理员");
            admin.setStatus(1);
            userMapper.insert(admin);

            // 关联管理员角色
            UserRole userRole = new UserRole();
            userRole.setUserId(admin.getId());
            userRole.setRoleId(1L); // 假设1是管理员角色ID
            userRoleMapper.insert(userRole);

            log.info("超级管理员账号初始化完成");
        }
    }
}